package com.example.myapplication;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class syncTest1 extends AppCompatActivity {

    private Button sendButton;
    private EditText message;
    private EditText ip;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_sync_test1);

        // 设置系统栏内边距
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        //
        message = findViewById(R.id.sendMessageToService);
        ip = findViewById(R.id.ip);



        // 初始化按钮
        sendButton = findViewById(R.id.sendButton);
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendMessage();
            }
        });
    }
//"192.168.100.223"
    private void sendMessage() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    // 1. 创建Socket对象，指定服务端的IP地址和端口
                    Socket socket = new Socket(ip.getText().toString(), 8888); // 替换为服务端的实际IP地址
                    DataOutputStream dos = new DataOutputStream(socket.getOutputStream());

                    // 2. 向服务端发送消息
                    dos.writeUTF(message.getText().toString());
                    dos.flush();

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(syncTest1.this, "消息发送成功", Toast.LENGTH_SHORT).show();
                        }
                    });

                    dos.close();
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            System.out.println("发送失败"+e.getMessage());
                            Toast.makeText(syncTest1.this, "发送失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }).start();
    }
}